package com.xtjc03.jms.service;

import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.jms.Message;
import javax.jms.MessageNotWriteableException;
import javax.jms.TextMessage;

@Service
public class JmsServiceImpl implements JmsService{

    @Autowired
    JmsTemplate jmsTemplate;

    @Override
    public void addSender(String destination, String msg) {
        addSender(destination, msg, -1);
    }

    @Override
    public void addSender(String destination, String msg, long delay) {
        ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
        try {
            jmsTemplate.setDeliveryDelay(delay);
            activeMQTextMessage.setText(msg);
        } catch (MessageNotWriteableException e) {
            e.printStackTrace();
        }
        jmsTemplate.convertAndSend(destination, activeMQTextMessage);
    }

    @Override
    public ActiveMQTextMessage addReceiver(String destination) {
        return addReceiver(destination, 2000);
    }

    @Override
    public ActiveMQTextMessage addReceiver(String destination, long delay) {
        ActiveMQTextMessage res = null;
        jmsTemplate.setReceiveTimeout(delay);
        res = (ActiveMQTextMessage) jmsTemplate.receive(destination);
        return res;
    }
}
